package org.springblade.modules.admin.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

/**
 * 飞书应用工具类
 * @author: Sharry
 * @createTime: 2023-12-21 10:29
 * @version: Version-1.0
 */
@Slf4j
public class FeiShuUtils {

	/**
	 * 应用 ID
	 */
	public static final String APPID = "cli_a5096c04ce38900b";

	/**
	 * 应用秘钥
	 */
	public static final String APPSECRET = "v6dXZelqLz0Weaz0v0u8cb2UVv6gQbiL";

	/**
	 * 德鲁伊所用的群机器人密钥
	 */
	public static final String SECRET = "fOCBzdaEuNGOSa6vtosxqf";

	/**
	 * 德鲁伊机器人 webhook
	 */
	public static String DRUID_WEBHOOK = "https://open.feishu.cn/open-apis/bot/v2/hook/d99364d3-99c3-44db-853c-3ee3358ed7fe";

	/**
	 * 获取应用的 access_token
	 * @param appId 应用 ID
	 * @param appSecret 应用秘钥
	 * @return 响应结果
	 * @throws Exception
	 */
	public static String getAccessToken(String appId, String appSecret) throws Exception {
		String res = null;
		// 创建一个 URL 对象
		HttpURLConnection connection = getTokenURLConnection();
		// 设置请求体
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("app_id", appId);
		jsonObject.put("app_secret", appSecret);
		connection.getOutputStream().write(jsonObject.toJSONString().getBytes());
		// 发送请求
		connection.connect();
		// 获取响应码
		int responseCode = connection.getResponseCode();
		// 如果响应码为 200，则表示请求成功
		if (responseCode == 200) {
			// 获取响应内容
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			StringBuilder response = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				response.append(line);
			}
			reader.close();
			// 打印响应内容
			res = response.toString();
		} else {
			// 请求失败
			log.info("请求失败，响应码{}",responseCode);
		}
		// 关闭连接
		connection.disconnect();
		return res;
	}

	private static HttpURLConnection getTokenURLConnection() throws IOException {
		URL url = new URL("https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal");
		// 打开一个 HTTP 连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		// 设置连接超时时间
		connection.setConnectTimeout(5000);
		// 设置读取超时时间
		connection.setReadTimeout(5000);
		// 设置请求方法为 POST
		connection.setRequestMethod("POST");
		// 设置 doOutput 属性为 true
		connection.setDoOutput(true);
		// 设置通用的请求属性
		connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
		return connection;
	}

	public static String getTenantAccessToken(String appId, String appSecret) throws Exception {
		JSONObject jsonObject = JSONObject.parseObject(getAccessToken(appId, appSecret));
		return jsonObject.getString("tenant_access_token");
	}

	/**
	 * create sign message
	 * @param secret 密钥
	 * @param timestamp 时间戳
	 * @return 签名
	 * @throws NoSuchAlgorithmException 异常信息
	 * @throws InvalidKeyException 异常信息
	 */
	public static String GenSign(String secret, int timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
		//把timestamp+"\n"+密钥当做签名字符串
		String stringToSign = timestamp + "\n" + secret;
		//使用HmacSHA256算法计算签名
		Mac mac = Mac.getInstance("HmacSHA256");
		mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
		byte[] signData = mac.doFinal(new byte[]{});
		return new String(Base64.encodeBase64(signData));
	}

	/**
	 * webhook发送机器人消息通用方法
	 */
	public static void sendMessage(String message) throws IOException {
		HashMap<String,String> contentMap = new HashMap<>(2);
		contentMap.put("text", message);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg_type", "text");
		jsonObject.put("content",  contentMap);
		// 签名信息
		int timestamp = (int) (System.currentTimeMillis() / 1000);
		String sign = null;
		try {
			sign = GenSign(SECRET, timestamp);
		} catch (NoSuchAlgorithmException | InvalidKeyException e) {
			throw new RuntimeException(e);
		}
		jsonObject.put("timestamp", timestamp);
		jsonObject.put("sign", sign);
		// 将 JSON 对象转换为字符串
		String payload = JSON.toJSONString(jsonObject);

		URL targetUrl = new URL(DRUID_WEBHOOK);
		// 创建一个 HTTP POST 请求
		HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoOutput(true);
		// 设置请求头
		connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
		connection.getOutputStream().write(payload.getBytes());
		int statusCode = connection.getResponseCode();
		log.info("HTTP status code: {}", statusCode);
	}

}
